import React, { RefObject } from 'react';
import { connect } from 'react-redux';
import styles from './index.module.scss';
import zhCN from 'antd/es/locale/zh_CN';
import {
	Row,
	Col,
	Button,
	Table,
	Space,
	Tooltip,
	Popconfirm,
	message,
	Input,
	ConfigProvider,
	Switch,
} from 'antd';
import {
	SearchOutlined,
	PlusCircleOutlined,
	// AreaChartOutlined,
	// PieChartOutlined,
	FormOutlined,
	DeleteOutlined,
	CloudUploadOutlined,
	FundViewOutlined,
	// RightCircleOutlined,
	// StopOutlined,
} from '@ant-design/icons';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import { AddNewModalComponent } from './components/AddNewModal';
import AddUploadFileModal from './components/AddUploadFileModal';
import { CreateDataSet } from '../DataSet/components/CreateDataSet';
import { addNewDataOriginal, getConnectList, deleteConnect, runResource, dataSetGetFiles } from 'src/services/DataManage/index';
import { addNewDataOriginalInput } from 'src/services/DataManage/type';

interface listItemType {
	name: string;
	id: string;
	type: string;
	typeName: string;
	effect: string;
}

interface IProps {
	record: listItemType;
	handleEdit: ( item: listItemType ) => void;
	handleDelete: ( item: listItemType ) => void;
	handleRoute: ( item: listItemType ) => void;
	handlePreview: any;
	handleRun:any;
	handleDataSet:any;
	btnAuth:any;
}

const iconStyle = {
	color: '#86BC25',
	marginRight: '8px',
};

//	操作栏组件
const OperateComponent = React.memo( ( props: IProps ) => {
	const isEnable = props.record.effect === 'ENABLE';
	return props.btnAuth.includes( 'bi_dataConnect_action' ) ? (
		<Space size="middle">
			<Tooltip placement="topRight" title="创建数据集">
				<Button
					disabled={!isEnable}
					type="text"
					onClick={() => props.handleDataSet( props.record )}
					icon={<PlusCircleOutlined className={isEnable ? styles.greenBtn : styles.grayBtn} />}
				></Button>
			</Tooltip>
			{/* <Tooltip placement="topRight" title="新增报表">
				<Button
					type="text"
					onClick={() => props.handleRoute( props.record )}
					icon={<AreaChartOutlined className={styles.greenBtn} />}
				></Button>
			</Tooltip> */}

			{/* <Tooltip placement="topRight" title="新增仪表盘">
				<Button
					type="text"
					icon={<PieChartOutlined className={styles.greenBtn} />}
				></Button>
			</Tooltip> */}
			<Tooltip placement="topRight" title="编辑">
				<Button
					type="text"
					icon={<FormOutlined className={styles.greenBtn} />}
					onClick={() => props.handleEdit( props.record )}
				></Button>
			</Tooltip>

			<Tooltip placement="topRight" title="数据预览">
				<Button
					type="text"
					icon={<FundViewOutlined className={styles.greenBtn} />}
					onClick={() => props.handlePreview( props.record )}
				></Button>
			</Tooltip>

			<Tooltip placement="topRight" title="删除">
				<Popconfirm
					okText="确定"
					cancelText="取消"
					title="确定删除这一项？"
					placement="bottom"
					onConfirm={() => props.handleDelete( props.record )}
				>
					<Button
						type="text"
						icon={<DeleteOutlined className={styles.greenBtn} />}
					></Button>
				</Popconfirm>
			</Tooltip>
			{/* <Tooltip placement="topRight" title={props.record.effect === 'DISABLE'? '启用' :'禁用'}>
				<Button
					type="text"
					icon={ props.record.effect === 'DISABLE' ? <RightCircleOutlined className={ styles.greenBtn }/> :<StopOutlined className={ styles.greenBtn }/>}
					onClick={() => props.handleRun( props.record )}
				></Button>
			</Tooltip> */}
		</Space>
	) : (
		<Space size="middle">
			<Tooltip placement="topRight" title="数据预览">
				<Button
					type="text"
					icon={<FundViewOutlined className={styles.greenBtn} />}
					onClick={() => props.handlePreview( props.record )}
				></Button>
			</Tooltip>
		</Space>
	);
} );
OperateComponent.displayName = 'OperateComponent';

/**
 * 页面使用class
 */
class DataManage extends React.Component<RouteComponentProps & { btnAuth:any }> {
	//	列表表头配置
	columns = [
		{
			title: '名称',
			// dataIndex: 'name',
			render: ( record: listItemType ) => {
				let icon = null;
				switch( record.typeName ) {
					case 'excel':
						icon = ( <span className="iconfont bdhexecl" style={iconStyle}></span> );
						break;
					case 'csv':
						icon = ( <span className="iconfont bdhexecl" style={iconStyle}></span> );
						break;
					case 'mysql':
						icon = ( <span className="iconfont bdhshujukumysql" style={iconStyle}></span> );
						break;
					case 'oracle':
						icon = ( <span className="iconfont bdhoracle" style={iconStyle}></span> );
						break;
					case 'sqlserver':
						icon = ( <span className="iconfont bdhSqlServer" style={iconStyle}></span> );
						break;
					case 'hive':
						icon = ( <span className="iconfont bdhhive" style={iconStyle}></span> );
						break;
					case 'hana':
						icon = ( <span className="iconfont bdhhana2x" style={iconStyle}></span> );
						break;
					default:
						icon = null;
						break;
				}
				return ( 
					<span className="bdh-link" onClick={() => this.handlePreview( record )}>
						{icon}{record.name}
					</span>
				);
			}
		},
		{
			title: '描述',
			dataIndex: 'comments',
		},
		{
			title: '类型',
			dataIndex: 'typeName',
			width: 100,
			// render: ( text: string ) => <span>{ text === '1' ? 'MySql8' : '' }</span>
			//	Mysql("1", "mysql"),// Oracle("3", "oracle"),// SQLServer("4", "sqlserver"),
			// Hive("5", "hive"),// Hive2("6", "hive2"),// File_Excel("7", "Excel"),// File_Csv("8", "Csv"),
		},
		{
			title: '数据库地址',
			dataIndex: 'address',
			width: 150
		},
		{
			title: '状态',
			// dataIndex: 'effect',
			width: 80,
			render: ( record: listItemType ) => {
				const btnAuth = this.props.btnAuth;
				return (
					<Switch checked={record.effect === 'ENABLE'}
						disabled={ !btnAuth.includes( 'bi_dataConnect_action' ) }
						loading={ this.state.effectLoading }
						onChange={() => { this.runResourceFunc( record ); }} />
				);
			}
		},
		{
			title: '操作',
			key: 'action',
			fixed: 'right' as 'right',
			width: 340,
			// eslint-disable-next-line react/display-name
			render: ( record: listItemType ) => (
				<OperateComponent
					record={record}
					handleRoute={this.handleRoute}
					handleEdit={this.handleEdit}
					handlePreview={this.handlePreview}
					handleDelete={this.handleDelete}
					handleRun={this.runResourceFunc}
					handleDataSet={this.handleDataSet}
					btnAuth={this.props.btnAuth}
				></OperateComponent>
			),
		},
	];

	//	声明当前页面变量
	state = {
		dateSetVisible: false,
		uploadModalVisible: false,
		modalVisible: false,
		pageSize: 10,
		page: 1,
		dataList: [],
		total: 0,
		editId: '',
		tableLoading: false,
		selectedRowKeys: [],
		kw: '',
		fileEdit: false, //据此判断是否编辑
		uploadItem: {},
		modalStatus: '', //编辑时状态
		treeData: [], //文件夹列表
		currentFolder: '', //当前文件夹
		curRow: null,
		effectLoading: false,
	};

	modalRef: RefObject<any> = React.createRef();
	dateSetRef: RefObject<any> = React.createRef();

	//	声明当前页面方法
	setPageSize = ( size: number ) => {
		this.setState( {
			pageSize: size,
		} );
	};

	//新增报表跳转
	handleRoute = ( item: listItemType ) => {
		this.props.history.push( `/dataManage/dataArrange?id=${item.id}` );
	};

	//数据预览跳转
	handlePreview = ( item ) => {
		console.log( item );
		let param = {
			pathname: '/dataManage/dataPreview',
			query: item,
		};
		this.props.history.push( param );
	};

	//	打开新建组件
	toggleModal = ( isShow: boolean ) => {
		this.setState( {
			modalVisible: isShow,
		} );

		if ( !isShow ) {
			this.setState( {
				editId: '',
				modalStatus: ''
			} );
		}
	};

	//上传本地文件modal切换
	toggleUploadModal = ( isShow: boolean ) => {
		this.setState( {
			uploadModalVisible: isShow,
		} );
		//当关闭的时候修改fileEdit状态
		if ( !isShow && this.state.fileEdit ) {
			this.setState( { fileEdit: false } );
		}
	};

	//上传是否编辑状态控制
	toggleUploadState = ( isShow: boolean ) => {
		this.setState( {
			fileEdit: isShow,
		} );
	};

	//	新增/编辑
	handleCreate = async ( data: addNewDataOriginalInput ) => {
		let saveInfo;
		//	如果是编辑
		if ( this.state.editId ) {
			saveInfo = Object.assign( data, { id: this.state.editId } );
		} else {
			saveInfo = Object.assign( data, );
		}
		const result = await addNewDataOriginal( saveInfo );
		if ( result.data && result.data.success ) {
			this.toggleModal( false );
			message.success( '创建成功' );
			this.getList();
		}
	};

	//	编辑
	handleEdit = ( item: listItemType ) => {
		//文件上传code集合
		const upload_code = [ '7', '8' ];
		//判断是否是文件上传
		if ( upload_code.indexOf( item.type ) !== -1 ) {
			this.setState( { uploadItem: item } );
			//文件上传弹框显示
			this.toggleUploadModal( true );
			//修改上传文件编辑状态
			this.toggleUploadState( true );
		} else {
			this.setState(
				{
					editId: item.id,
					modalVisible: true,
					modalStatus: item.effect,
				},
				() => {
					setTimeout( () => {
						this.modalRef.current.setFieldsValue( item );
					}, 100 );
				}
			);
		}
	};
	
	//启用禁用 
	runResourceFunc = async ( item:listItemType ) => {
		this.setState( { effectLoading: true } );
		const info = await runResource( { 
			data: { id: item.id, effect: item.effect === 'DISABLE'?'ENABLE':'DISABLE' }
		} );
		if ( info.data.success ) {
			// item.effect === 'DISABLE'? message.success( '启用成功' ) :message.success( '禁用成功' );
			// this.getList();
			let dataList = JSON.parse( JSON.stringify( this.state.dataList ) );
			let idx = dataList.findIndex( o => o.id === item.id );
			dataList.splice( idx, 1, info.data.data );
			this.setState( {
				effectLoading: false,
				dataList,
			} );
		}


	}

	//	删除
	handleDelete = async ( item: listItemType ) => {
		const info = await deleteConnect( { data: item.id } );
		if ( info.data.success ) {
			message.success( '删除成功' );
			this.getList();
		}
	};

	//批量删除
	handleDeletMany = () => {
		console.log( '批量删除' );
	};

	//确认批量删除
	confirm = () => {
		message.success( '批量删除成功' );
	};

	handlePageChange = ( pageNumber: number ) => {
		this.setState(
			{
				page: pageNumber,
			},
			() => {
				this.getList();
			}
		);
	};

	getList = async () => {
		this.setState( {
			tableLoading: true,
		} );
		const info = await getConnectList( {
			page: this.state.page,
			size: this.state.pageSize,
			name: this.state.kw,
		} );
		if ( info.data.success ) {
			this.setState( {
				dataList: info.data.data.rows,
				total: info.data.data.total,
			} );
		}
		this.setState( {
			tableLoading: false,
		} );
	};

	// 获取文件夹数据
	getFolderList = async () => {
		const info = await dataSetGetFiles( { data: '' } );
		if( info.data.success ) {
			this.setState( {
				treeData: info.data.data.map( item => {return { key: item.id,title: item.tableName,...item };} )
			} );
		}
	};

	// 打开/关闭数据集弹窗
	toggleDateSet = ( value:boolean ) => {
		this.setState( { dateSetVisible: value } );
	};

	handleDataSet = ( row ) => {
		let tableName = ~[ 'excel', 'csv' ].indexOf( row.typeName ) ? row.dbName : null;
		this.toggleDateSet( true );
		this.setState( {
			curRow: {
				refSourceId: row.id,
				tableName,
			}
		}, () => {
			this.dateSetRef.current.setFieldsValue( this.state.curRow );
		} );
	};

	// 创建数据集成功回调
	createDateSet = () => {
		//...
	};

	//	生命周期
	async componentDidMount() {
		// 发请求获取列表
		this.getList();
		this.getFolderList();

		// // 从props取route参数
		// const props = this.props;
	}

	//多选
	onSelectChange = ( selectedRowKeys ) => {
		this.setState( { selectedRowKeys } );
	};

	//搜索框改变时
	handleChange = ( e ) => {
		this.setState( { kw: e.target.value } );
	};

	//搜索框回车事件
	handelPressEnter = ( e ) => {
		// 发请求获取列表
		this.getList();
	};

	//	渲染
	render(): React.ReactNode {
		// const rowSelection = {
		// 	selectedRowKeys: this.state.selectedRowKeys,
		// 	onChange: this.onSelectChange,
		// };
		const btnAuth = this.props.btnAuth;
		return (
			<div className={styles.page}>
				<div className={styles.wrap}>
					<Row justify="space-between" style={{ textAlign: 'left' }}>
						<Col span={12}>
							{/*批量删除*/}
							{/*<Popconfirm*/}
							{/*	title="确认批量删除?"*/}
							{/*	onConfirm={this.confirm}*/}
							{/*	okText="确定"*/}
							{/*	cancelText="取消"*/}
							{/*>*/}
							{/*	<Button*/}
							{/*		type='primary'*/}
							{/*		icon={ <DeleteOutlined />}*/}
							{/*		onClick={this.handleDeletMany}*/}
							{/*		className='grey-button'>批量删除</Button>*/}
							{/*</Popconfirm>*/}
							{
								btnAuth.includes( 'bi_dataConnect_addSource' ) && (
									<Button
										type="primary"
										icon={<PlusCircleOutlined />}
										onClick={() => this.toggleModal( true )}
									>
										添加数据源
									</Button>
								)
							}
							{
								btnAuth.includes( 'bi_dataConnect_upload' ) && (
									<Button
										icon={<CloudUploadOutlined />}
										onClick={() => this.toggleUploadModal( true )}
										className="grey-button"
									>
										上传本地文件
									</Button>
								)
							}
						</Col>
						<Col xs={ 24 } sm={ 5 } md={ 5 } lg={ 5 } xl={ 5 } style={ { textAlign: 'right' } }>
							<Input
								placeholder="请输入名称回车搜索"
								onChange={this.handleChange}
								onPressEnter={this.handelPressEnter}
								prefix={<SearchOutlined />}
							/>
						</Col>
					</Row>

					<div>
						<ConfigProvider locale={zhCN}>
							<Table
								// rowSelection={rowSelection}
								loading={this.state.tableLoading}
								scroll={{ x: '100%' }}
								tableLayout="fixed"
								columns={this.columns}
								dataSource={this.state.dataList}
								className={styles.tableMargin}
								bordered={true}
								rowKey={( row: listItemType ) => row.id}
								size="middle"
								pagination={{
									showSizeChanger: true,
									pageSize: this.state.pageSize,
									total: this.state.total,
									onChange: this.handlePageChange,
									onShowSizeChange: ( current, size ) => this.setPageSize( size ),
									showTotal: ( total ) => `共 ${total} 条`,
									showQuickJumper: true,
								}}
							/>
						</ConfigProvider>
					</div>

					{/*文件上传弹框*/}
					<AddUploadFileModal
						getList={this.getList}
						data={this.state.uploadItem} //将编辑的数据信息传递到弹框
						fileEdit={this.state.fileEdit}
						uploadModalVisible={this.state.uploadModalVisible}
						closeModal={this.toggleUploadModal}
					></AddUploadFileModal>

					{/*新建连接弹框*/}
					<AddNewModalComponent
						ref={this.modalRef}
						modalVisible={this.state.modalVisible}
						modalStatus={this.state.modalStatus}
						onCreate={this.handleCreate}
						closeModal={this.toggleModal}
					></AddNewModalComponent>

					{/* 创建数据集 */}
					<CreateDataSet
						ref={ this.dateSetRef }
						data={ this.state.curRow }
						folderId={ this.state.currentFolder }
						treeData={ this.state.treeData }
						modalVisible={ this.state.dateSetVisible }
						onCreate={ this.createDateSet }
						closeModal={ this.toggleDateSet }/>
				</div>
			</div>
		);
	}
}

//	映射state到当前组件
const mapStateToProps = ( state ) => {
	return {
		btnAuth: state.btnAuth,
	};
};

export default withRouter( connect( mapStateToProps )( DataManage ) );
